﻿/*
 *  Copyright (c) 2010, Steven Wang
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *      
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  
 *  twitterSina at http://twitterSina.appspot.com
 *  twitterSina code at http://twitterSina.googlecode.com
 * 	
 */
package twitterSina.robot;

import java.util.ArrayList;
import java.util.List;

import twitter4j.Status;
import twitterSina.DiguAPI;
import twitterSina.RenrenHttp;
import twitterSina.SinaHttp;
import twitterSina.TwitterAPI;
import twitterSina.ZuosaAPI;
import twitterSina.common.AccountType;
import twitterSina.common.DateHelp;
import twitterSina.common.DesEncrypt;
import twitterSina.common.HttpHelp;
import twitterSina.common.SysLogType;
import twitterSina.persistence.Account;
import twitterSina.persistence.SysLog;
import twitterSina.persistence.SysLogDao;
import twitterSina.persistence.TwitterNotify;
import twitterSina.persistence.TwitterNotifyDao;
import twitterSina.persistence.User;
import twitterSina.persistence.UserDao;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.xmpp.Message;

/**
 * 机器人服务类
 * @author Steven Wang <http://blog.stevenwang.name>
 */
public class RobotService 
{
	private RobotService(){}
	
	private static RobotService instance = null;
	
	public static synchronized RobotService getInstance()
	{
		if(instance == null)
		{
			instance = new RobotService();
		}
		return instance;
	}
	
	/**
	* 根据用户ID获取用户
	* @param UserId，用户ID
	* @return，符合条件的用户
	*/
	public User getUserByUserId(String userId)
	{
		User user = UserDao.getInstance().getByUserId(userId);
		if(user != null)
		{
			user.setAccountList(UserDao.getInstance().
				getUserAccountList(user));
		}
		return user;
	}
	
	/**
	* 添加一个新用户
	* @param userId，用户ID
	* @return，添加的用户实体
	*/
	public User newUser(String userId)
	{
		User user = new User();
		user.setUserId(userId);
		user.setUserPwd("000000");
		user.setIsInUse(true);
		user.setPushCount(0);
		user.setStartTime(DateHelp.getLocalDateTime());
		user.setLastActiveTime(DateHelp.getLocalDateTime());
		UserDao.getInstance().addOrUpdateUser(user);
		return user;
	}
	
	/**
	* 绑定同步账号
	* @param message，用户发送的message
	* @param user，用户实体
	*/
	public void doBind(Message message, User user)
	{
		String messageBody = message.getBody().trim();
		StringBuffer userNameSb = new StringBuffer();   //for write log
		List<Account> accountList = RobotMsg.getInstance().
			getAccounts(user, messageBody, userNameSb);
		if(accountList == null)   //输入不正确
		{
			RobotMsg.getInstance().sendMessage(message, RobotMsg.OperateError);
			return;
		}
		//验证账户
		String checkResult = checkAccountLogin(accountList);
		//对密码进行加密编码
		for(Account account : accountList)
		{
			account.setUserPwd
				(DesEncrypt.getEncString(account.getUserPwd()));
		}
		//保留已有的账户
		for(Account accountOld : user.getAccountList())
		{
			boolean isExist = false;
			for(Account accountNew : accountList)
			{
				if(accountOld.getAccountType() ==
					accountNew.getAccountType())
				{
					isExist = true;
					break;
				}
			}
			if(!isExist)
			{
				Account account = new Account();
				account.setAccountType(accountOld.getAccountType());
				account.setIsAuth(accountOld.getIsAuth());
				account.setUser(user);
				account.setUserName(accountOld.getUserName());
				account.setUserPwd(accountOld.getUserPwd());
				accountList.add(account);
			}
		}
		//保存账户信息
		UserDao.getInstance().deleteUserAccountList(user.getUserId());
		user.setAccountList(accountList);
		user.setLastActiveTime(DateHelp.getLocalDateTime());
		if(UserDao.getInstance().addOrUpdateUser(user))
		{
			if(checkResult == null)   //保存成功，验证成功
			{
				RobotMsg.getInstance().sendMessage(message, RobotMsg.BindSuc);
				checkResult = "验证成功！";
			}
			else   //保存成功，验证失败
			{
				RobotMsg.getInstance().sendMessage(message, 
						checkResult + RobotMsg.BindFail);
			}
		}
		else   //保存失败
		{
			RobotMsg.getInstance().sendMessage(message, RobotMsg.BindFail);
		}
		
		//更新Twitter消息提示
		TwitterNotify twitterNotify = TwitterNotifyDao.
			getInstance().getByUserId(user.getUserId());
		if(twitterNotify != null)
		{
			twitterNotify.setIsNotify(false);
			TwitterNotifyDao.getInstance().
				addOrUpdateTwitterNotify(twitterNotify);
		}
		
		//写系统日志
		SysLog log = new SysLog();
		log.setUserId(user.getUserId());
		log.setLogTime(DateHelp.getLocalDateTime());
		log.setLogType(SysLogType.doBind);
		log.setLogContent(new Text(userNameSb.toString() + "@" + checkResult));
		SysLogDao.getInstance().addSysLog(log);
	}
	
	/**
	* 发布消息
	* @param message，用户发送的message
	* @param user，用户实体
	* @param messageBody，用户发送的消息内容
	*/
	public void doPublish(Message message, User user)
	{
		//计算可用的同步账号个数
		int validAccountCount = 0;
		for(Account account : user.getAccountList())
		{
			if(account.getIsAuth())
			{
				validAccountCount++;
				break;
			}
		}
		if(validAccountCount == 0)   //无可用的同步账号
		{
			RobotMsg.getInstance().sendMessage(message, RobotMsg.NotBind);
			return;
		}
		String messageBody = message.getBody().trim();
		if(messageBody.length() > 140)
		{
			RobotMsg.getInstance().sendMessage(message, RobotMsg.PC2Long + 
					"目前是" + messageBody.length() + "个字。");
			return;
		}
		StringBuffer userNameSb = new StringBuffer();   //for write log
		//发布消息
		String publishResult = publishByAccount(user.getAccountList(), 
				messageBody, userNameSb);
		if(publishResult == null)   //发布成功
		{
			RobotMsg.getInstance().sendMessage(message, RobotMsg.PublishSuc);
			publishResult = "发布成功！";
		}
		else
		{
			RobotMsg.getInstance().sendMessage(message, publishResult);
		}
		//更新用户信息
		user.setLastActiveTime(DateHelp.getLocalDateTime());
		user.setPushCount(user.getPushCount() + 1);
		UserDao.getInstance().addOrUpdateUser(user);
		
		//写系统日志
		SysLog log = new SysLog();
		log.setUserId(user.getUserId());
		log.setLogTime(DateHelp.getLocalDateTime());
		log.setLogType(SysLogType.doPublish);
		log.setLogContent(new Text(userNameSb.toString() + "[" + 
				messageBody + "]@" + publishResult));
		SysLogDao.getInstance().addSysLog(log);
	}
	
	/**
	* 取消所有绑定
	* @param message，用户发送的message
	* @param user，用户实体
	*/
	public void doRemove(Message message, User user)
	{
		String accountNames = user.getAccountNames();
		user.setAccountList(null);
		SysLog log = new SysLog();
		if(UserDao.getInstance().deleteUserAccountList(user.getUserId()))
		{
			RobotMsg.getInstance().sendMessage(message, RobotMsg.RemoveSuc);
			log.setLogContent(new Text(accountNames + "@" + 
					RobotMsg.RemoveSuc));
		}
		else
		{
			RobotMsg.getInstance().sendMessage(message, RobotMsg.RemoveFail);
			log.setLogContent(new Text(accountNames + "@" + 
					RobotMsg.RemoveFail));
		}
		
		//更新用户信息
		user.setLastActiveTime(DateHelp.getLocalDateTime());
		UserDao.getInstance().addOrUpdateUser(user);
		
		//更新Twitter消息提示
		TwitterNotify twitterNotify = TwitterNotifyDao.
			getInstance().getByUserId(user.getUserId());
		if(twitterNotify != null)
		{
			twitterNotify.setIsNotify(false);
			TwitterNotifyDao.getInstance().
				addOrUpdateTwitterNotify(twitterNotify);
		}
		
		//写系统日志
		log.setUserId(user.getUserId());
		log.setLogTime(DateHelp.getLocalDateTime());
		log.setLogType(SysLogType.doRemove);
		SysLogDao.getInstance().addSysLog(log);
	}
	
	/**
	* 查看用户绑定账号信息
	* @param message，用户发送的message
	* @param user，用户实体
	*/
	public void doStatus(Message message, User user)
	{
		if(user.getAccountList().size() == 0)
		{
			RobotMsg.getInstance().sendMessage(message, RobotMsg.NotBind);
			return;
		}
		StringBuffer userInfo = new StringBuffer();
		userInfo.append(RobotMsg.StatusHead);
		for(Account account : user.getAccountList())
		{
			switch(account.getAccountType())
			{
				case AccountType.TWITTER:
					userInfo.append(AccountType.TWITTERNAME);
					break;
				case AccountType.SINA:
					userInfo.append(AccountType.SINANAME);
					break;
				case AccountType.RENREN:
					userInfo.append(AccountType.RENRENNAME);
					break;
				case AccountType.DIGU:
					userInfo.append(AccountType.DIGUNAME);
					break;
				case AccountType.ZUOSA:
					userInfo.append(AccountType.ZUOSANAME);
					break;
			}
			userInfo.append("-");
			userInfo.append(account.getUserName());
			if(account.getIsAuth())
			{
				userInfo.append("\n");
			}
			else
			{
				userInfo.append("(未验证)\n");
			}
		}
		RobotMsg.getInstance().sendMessage(message, userInfo.toString());
		
		//更新用户信息
		user.setLastActiveTime(DateHelp.getLocalDateTime());
		UserDao.getInstance().addOrUpdateUser(user);
	}
	
	/**
	* 设置Twitter消息提示
	* @param message，用户发送的message
	* @param user，用户实体
	* @param isNotify，打开/关闭消息提示
	*/
	public void doTwitterNotifyChange(Message message, User user, 
			boolean isNotify)
	{
		TwitterNotify twitterNotify = TwitterNotifyDao.
			getInstance().getByUserId(user.getUserId());
		
		//没有设置消息提示时取消消息提示操作
		if(twitterNotify == null && !isNotify)
		{
			RobotMsg.getInstance().sendMessage(message, 
			RobotMsg.NotSetTwitterNotify);
			return;
		}
		
		//若为打开消息提示
		if(isNotify)
		{
			//还没有设置过消息提示
			if(twitterNotify == null)
			{
				twitterNotify = new TwitterNotify();
				twitterNotify.setUserId(user.getUserId());
				twitterNotify.setLastNotifyMsgId(0);
				twitterNotify.setNotifyCount(0);
			}
			boolean find = false;
			for(Account account : user.getAccountList())
			{
				if(account.getAccountType() == AccountType.TWITTER &&
						account.getIsAuth())
				{
					twitterNotify.setUserJID(message.getFromJid().getId());
					twitterNotify.setUserName(account.getUserName());
					twitterNotify.setUserPwd(account.getUserPwd());
					find = true;
					break;
				}
			}
			if(!find)
			{
				RobotMsg.getInstance().sendMessage(message, 
						RobotMsg.NotBindTwitter);
				return;
			}
		}
		twitterNotify.setIsNotify(isNotify);
		TwitterNotifyDao.getInstance().
			addOrUpdateTwitterNotify(twitterNotify);
		
		String result = "";
		if(isNotify)
			result = RobotMsg.SetTwitterNotifyOnSuc;
		else
			result = RobotMsg.SetTwitterNotifyOffSuc;
		RobotMsg.getInstance().sendMessage(message, result);
		
		//更新用户信息
		user.setLastActiveTime(DateHelp.getLocalDateTime());
		UserDao.getInstance().addOrUpdateUser(user);
		
		//写系统日志
		SysLog log = new SysLog();
		log.setUserId(user.getUserId());
		log.setLogTime(DateHelp.getLocalDateTime());
		log.setLogType(SysLogType.doTwitterNotifyChange);
		log.setLogContent(new Text(result));
		SysLogDao.getInstance().addSysLog(log);
	}
	
	/**
	* 获取Twitter最新20条更新
	* @param message，用户发送的message
	* @param user，用户实体
	*/
	public void doTwitterHome(Message message, User user)
	{
		for(Account account : user.getAccountList())
		{
			if(account.getAccountType() == AccountType.TWITTER &&
					account.getIsAuth())
			{
				List<Status> statusList = new TwitterAPI().
					getHomeTimeline(account.getUserName(), 
					DesEncrypt.getDesString(account.getUserPwd()));
				if(statusList == null || statusList.isEmpty())
				{
					RobotMsg.getInstance().sendMessage(message, RobotMsg.NoTweet);
					return;
				}
				boolean isForGTalk = false;
				if(message.getFromJid().getId().toLowerCase().indexOf("talk.v") > 0)
				{
					isForGTalk = true;
				}
				String result = RobotMsg.getInstance().getTweetListStr(statusList, 
						0, isForGTalk);
				RobotMsg.getInstance().sendMessage(message, result);
				
				//更新用户信息
				user.setLastActiveTime(DateHelp.getLocalDateTime());
				UserDao.getInstance().addOrUpdateUser(user);
				
				TwitterNotify tn = TwitterNotifyDao.
					getInstance().getByUserId(user.getUserId());
				if(tn != null)
				{
					tn.setLastNotifyMsgId(statusList.get(0).getId());
					tn.setLastNotifyTime(DateHelp.getLocalDateTime());
					tn.setNotifyCount(tn.getNotifyCount() + 1);
					TwitterNotifyDao.getInstance().addOrUpdateTwitterNotify(tn);
				}
				
				//写系统日志
				SysLog log = new SysLog();
				log.setUserId(user.getUserId());
				log.setLogTime(DateHelp.getLocalDateTime());
				log.setLogType(SysLogType.doTwitterHome);
				log.setLogContent(new Text("获取Twitter最新20条更新"));
				SysLogDao.getInstance().addSysLog(log);
				return;
			}
		}
		RobotMsg.getInstance().sendMessage(message, 
				RobotMsg.NotBindTwitter);
	}
	
	/**
	* 获取Twitter最新20条回复
	* @param message，用户发送的message
	* @param user，用户实体
	*/
	public void doTwitterReply(Message message, User user)
	{
		for(Account account : user.getAccountList())
		{
			if(account.getAccountType() == AccountType.TWITTER &&
					account.getIsAuth())
			{
				List<Status> statusList = new TwitterAPI().
					getReply(account.getUserName(), 
					DesEncrypt.getDesString(account.getUserPwd()));
				if(statusList == null || statusList.isEmpty())
				{
					RobotMsg.getInstance().sendMessage(message, RobotMsg.NoTweet);
					return;
				}
				boolean isForGTalk = false;
				if(message.getFromJid().getId().toLowerCase().indexOf("talk.v") > 0)
				{
					isForGTalk = true;
				}
				String result = RobotMsg.getInstance().getTweetListStr(statusList, 
						0, isForGTalk);
				RobotMsg.getInstance().sendMessage(message, result);
				
				//更新用户信息
				user.setLastActiveTime(DateHelp.getLocalDateTime());
				UserDao.getInstance().addOrUpdateUser(user);
				
				TwitterNotify tn = TwitterNotifyDao.
				getInstance().getByUserId(user.getUserId());
				if(tn != null)
				{
					tn.setLastNotifyTime(DateHelp.getLocalDateTime());
					tn.setNotifyCount(tn.getNotifyCount() + 1);
					TwitterNotifyDao.getInstance().addOrUpdateTwitterNotify(tn);
				}
				
				//写系统日志
				SysLog log = new SysLog();
				log.setUserId(user.getUserId());
				log.setLogTime(DateHelp.getLocalDateTime());
				log.setLogType(SysLogType.doTwitterReply);
				log.setLogContent(new Text("获取Twitter最新20条回复"));
				SysLogDao.getInstance().addSysLog(log);
				return;
			}
		}
		RobotMsg.getInstance().sendMessage(message, 
			RobotMsg.NotBindTwitter);
	}
	
	/**
	* 以回复的形式发布Twitter消息
	* @param message，用户发送的message
	* @param user，用户实体
	*/
	public void doTwitterReplyPublish(Message message, User user)
	{
		for(Account account : user.getAccountList())
		{
			if(account.getAccountType() == AccountType.TWITTER &&
					account.getIsAuth())
			{
				//判断参数，准备数据
				String tmp[] = message.getBody().trim().split("\\s+");
				if(tmp.length < 4)
				{
					RobotMsg.getInstance().sendMessage(message, 
						RobotMsg.OperateError);
					return;
				}
				long statusId = 0;
				try
				{
					statusId = Long.parseLong(tmp[1]);
				}
				catch(Exception e)
				{
					RobotMsg.getInstance().sendMessage(message, 
						RobotMsg.OperateError);
					return;
				}
				String status = "";
				for(int i = 2, n = tmp.length;i < n;i++)
				{
					status += tmp[i] + " ";
				}
				if(status.length() > 140)
				{
					RobotMsg.getInstance().sendMessage(message, RobotMsg.PC2Long + 
							"目前是" + status.length() + "个字。");
					return;
				}
				
				//发送消息
				StringBuffer sb = new StringBuffer();
				boolean fail = true;
				int retryThreshold = 3;   //发布失败时,重试次数的阈值
				int retryCount = 0;
				TwitterAPI twitter = new TwitterAPI();
				while(fail && 
						retryCount < retryThreshold)
				{
					fail = !twitter.publishTwitter(account.getUserName(), 
								DesEncrypt.getDesString(account.getUserPwd()), 
								status, statusId);
					retryCount++;
				}
				
				//反馈发送结果，构造系统日志字符串
				sb.append(AccountType.TWITTERNAME);
				sb.append("-");
				sb.append(account.getUserName());
				sb.append(",[");
				sb.append(status);
				sb.append("]@");
				if(fail)
				{
					sb.append("发布失败！");
					RobotMsg.getInstance().sendMessage(message, 
						RobotMsg.PublishFail);
				}
				else
				{
					sb.append("发布成功！");
					RobotMsg.getInstance().sendMessage(message, 
						RobotMsg.PublishSuc);
				}
				
				//更新用户信息
				user.setLastActiveTime(DateHelp.getLocalDateTime());
				user.setPushCount(user.getPushCount() + 1);
				UserDao.getInstance().addOrUpdateUser(user);
				
				//写系统日志
				SysLog log = new SysLog();
				log.setUserId(user.getUserId());
				log.setLogTime(DateHelp.getLocalDateTime());
				log.setLogType(SysLogType.doPublish);
				log.setLogContent(new Text(sb.toString()));
				SysLogDao.getInstance().addSysLog(log);
				return;
			}
		}
		RobotMsg.getInstance().sendMessage(message, 
			RobotMsg.NotBindTwitter);
	}
	
	/**
	* 选择同步源发布消息
	* @param message，用户发送的message
	* @param user，用户实体
	*/
	public void doSePublish(Message message, User user)
	{
		//计算可用的同步账号个数
		int validAccountCount = 0;
		for(Account account : user.getAccountList())
		{
			if(account.getIsAuth())
			{
				validAccountCount++;
				break;
			}
		}
		if(validAccountCount == 0)   //无可用的同步账号
		{
			RobotMsg.getInstance().sendMessage(message, RobotMsg.NotBind);
			return;
		}
		String messageBody = message.getBody();
		String status = messageBody.replaceAll("-t", "")
				.replaceAll("-s", "").replaceAll("-r", "")
				.replaceAll("-d", "").replaceAll("-z", "").trim();
		if(status.length() > 140)
		{
			RobotMsg.getInstance().sendMessage(message, RobotMsg.PC2Long + 
					"目前是" + status.length() + "个字。");
			return;
		}
		
		//构造要发布的消息的账号集合
		List<Account> accountList = new ArrayList<Account>();
		String str = "";
		for(Account account : user.getAccountList())
		{
			str = "";
			switch(account.getAccountType())
			{
				case AccountType.TWITTER:
					str = "-t";
					break;
				case AccountType.SINA:
					str = "-s";
					break;
				case AccountType.RENREN:
					str = "-r";
					break;
				case AccountType.DIGU:
					str = "-d";
					break;
				case AccountType.ZUOSA:
					str = "-z";
					break;
			}
			if(!str.isEmpty() && messageBody.indexOf(str) > -1)
			{
				accountList.add(account);
			}
		}
		
		StringBuffer userNameSb = new StringBuffer();   //for write log
		//发布消息
		String publishResult = publishByAccount(accountList, 
				status, userNameSb);
		if(publishResult == null)   //发布成功
		{
			RobotMsg.getInstance().sendMessage(message, RobotMsg.PublishSuc);
			publishResult = "发布成功！";
		}
		else
		{
			RobotMsg.getInstance().sendMessage(message, publishResult);
		}
		//更新用户信息
		user.setLastActiveTime(DateHelp.getLocalDateTime());
		user.setPushCount(user.getPushCount() + 1);
		UserDao.getInstance().addOrUpdateUser(user);
		
		//写系统日志
		SysLog log = new SysLog();
		log.setUserId(user.getUserId());
		log.setLogTime(DateHelp.getLocalDateTime());
		log.setLogType(SysLogType.doPublish);
		log.setLogContent(new Text(userNameSb.toString() + "[" + 
				status + "]@" + publishResult));
		SysLogDao.getInstance().addSysLog(log);
	}
	
	/**
	* 验证同步账号
	* @param accountList，同步账号集合
	* @return，验证结果
	*/
	private String checkAccountLogin(List<Account> accountList)
	{
		StringBuffer sb = new StringBuffer();
		boolean fail = false;
		String result = null;
		for(Account account : accountList)
		{
			switch(account.getAccountType())
			{
				case AccountType.TWITTER:
					if(!new TwitterAPI().loginTwitter
							(account.getUserName(), account.getUserPwd()))
					{
						fail = true;
						sb.append(AccountType.TWITTERNAME);
						sb.append(",");
						account.setIsAuth(false);
					}
					else
					{
						account.setIsAuth(true);
					}
					break;
				case AccountType.SINA:
					if(new SinaHttp().loginSina
							(account.getUserName(), account.getUserPwd()) == null)
					{
						fail = true;
						sb.append(AccountType.SINANAME);
						sb.append(",");
						account.setIsAuth(false);
					}
					else
					{
						account.setIsAuth(true);
					}
					break;
				case AccountType.RENREN:
					if(new RenrenHttp().loginRenren
							(account.getUserName(), account.getUserPwd()) == null)
					{
						fail = true;
						sb.append(AccountType.RENRENNAME);
						sb.append(",");
						account.setIsAuth(false);
					}
					else
					{
						account.setIsAuth(true);
					}
					break;
				case AccountType.DIGU:
					if(!new DiguAPI().loginDigu
							(account.getUserName(), account.getUserPwd()))
					{
						fail = true;
						sb.append(AccountType.DIGUNAME);
						sb.append(",");
						account.setIsAuth(false);
					}
					else
					{
						account.setIsAuth(true);
					}
					break;
				case AccountType.ZUOSA:
					if(!new ZuosaAPI().loginZuosa
							(account.getUserName(), account.getUserPwd()))
					{
						fail = true;
						sb.append(AccountType.ZUOSANAME);
						sb.append(",");
						account.setIsAuth(false);
					}
					else
					{
						account.setIsAuth(true);
					}
					break;
			}
		}
		if(fail)
		{
			result = sb.toString();
			result = result.substring(0, result.length() - 1);
			result += "身份验证失败！";
		}
		return result;
	}

	/**
	* 按同步账号发布消息
	* @param accountList，同步账号集合
	* @param publishContent，发布内容
	* @param userNameSb，拼接账户名，用于记录日志
	* @return，发布结果
	*/
	private String publishByAccount(List<Account> accountList, String publishContent, 
			StringBuffer userNameSb)
	{
		publishContent = HttpHelp.processContent(publishContent);
		StringBuffer sb = new StringBuffer();
		boolean fail = true;
		String publishResult = null;
		int retryThreshold = 3;   //发布失败时,重试次数的阈值
		int retryCount = 0;
		for(Account account : accountList)
		{
			if(!account.getIsAuth())
			{
				continue;
			}
			String pwd = DesEncrypt.getDesString(account.getUserPwd());
			retryCount = 0;
			fail = true;
			switch(account.getAccountType())
			{
				case AccountType.TWITTER:
					TwitterAPI twitter = new TwitterAPI();
					while(fail && 
							retryCount < retryThreshold)
					{
						fail = !twitter.publishTwitter(account.getUserName(), 
									pwd, publishContent);
						retryCount++;
					}
					if(fail)
					{
						sb.append(AccountType.TWITTERNAME);
						sb.append(",");
					}
					userNameSb.append(AccountType.TWITTERNAME);
					break;
				case AccountType.SINA:
					SinaHttp sina = new SinaHttp();
					while(fail && 
							retryCount < retryThreshold)
					{
						String sinaCookie = sina.loginSina(account.getUserName(), pwd);
						fail = sinaCookie == null || 
							!sina.publishSina(sinaCookie, publishContent);
						retryCount++;
					}
					if(fail)
					{
						sb.append(AccountType.SINANAME);
						sb.append(",");
					}
					userNameSb.append(AccountType.SINANAME);
					break;
				case AccountType.RENREN:
					RenrenHttp renren = new RenrenHttp();
					while(fail && 
							retryCount < retryThreshold)
					{
						String renrenCookie = renren.loginRenren(account.getUserName(), pwd);
						fail = renrenCookie == null || 
							!renren.publishRenren(renrenCookie, publishContent);
						retryCount++;
					}
					if(fail)
					{
						sb.append(AccountType.RENRENNAME);
						sb.append(",");
					}
					userNameSb.append(AccountType.RENRENNAME);
					break;
				case AccountType.DIGU:
					DiguAPI digu = new DiguAPI();
					while(fail && 
							retryCount < retryThreshold)
					{
						fail = !digu.publishDigu(account.getUserName(), 
									pwd, publishContent);
						retryCount++;
					}
					if(fail)
					{
						sb.append(AccountType.DIGUNAME);
						sb.append(",");
					}
					userNameSb.append(AccountType.DIGUNAME);
					break;
				case AccountType.ZUOSA:
					ZuosaAPI zuosa = new ZuosaAPI();
					while(fail && 
							retryCount < retryThreshold)
					{
						fail = !zuosa.publishZuosa(account.getUserName(), 
									pwd, publishContent);
						retryCount++;
					}
					if(fail)
					{
						sb.append(AccountType.ZUOSANAME);
						sb.append(",");
					}
					userNameSb.append(AccountType.ZUOSANAME);
					break;
			}
			userNameSb.append("-");
			userNameSb.append(account.getUserName());
			userNameSb.append(",");
		}
		if(fail)
		{
			publishResult = sb.toString();
			publishResult = publishResult.substring(0, publishResult.length() - 1);
			publishResult += "发布失败！";
		}
		return publishResult;
	}
}
